//
//  YYECompose.swift
//  weibo14
//
//  Created by mac on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import pop

class YYECompose: UIView {

    var tagerVC:YYEMainViewController?
    
    // 装有菜单按钮的数组
    var buttons: [YYEComposeButton] = [YYEComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    func show(vc:YYEMainViewController) {
    
        vc.view.addSubview(self)
        
        tagerVC = vc
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        frame = UIScreen.mainScreen().bounds
        
        // backgroundColor = UIColor.yellowColor()
       
        
        let image = getUIScreen()
    
        let bgImageView = UIImageView(image: image.applyLightEffect())
        
        addSubview(bgImageView)
        addSubview(adView)
        // 添加约束
        adView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-200)
            
        }
      
        // 添加图片
        addButton()
    }
   
    private func addButton(){
    
        let itemW: CGFloat = 80
        let itemH: CGFloat = 110
        
        // 每一个按钮之前的间距
        let itemMargin = (SCREENW - 3 * itemW)/4
        
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        
        // 数组
        var menuInfos = [YYEComposeMenuInfo]()
        // 进行字典转模型
        for dict in array {
            let info = YYEComposeMenuInfo(dict: (dict as! [String: AnyObject]))
            menuInfos.append(info)
        }
        
        for (i,info) in menuInfos.enumerate() {
        
            let button = YYEComposeButton()
            
            button.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.menuInfo = info
            
            buttons.append(button)
            
            button.frame.size = CGSize(width: itemW, height: itemH)
            
          

            addSubview(button)

            // 计算位置
            let col = i%3
            let row = i/3
            
            // 设置x值
            button.frame.origin.x = CGFloat(col + 1) * itemMargin + CGFloat(col) * itemW
            // y值
            button.frame.origin.y = CGFloat(row) * (itemH + itemMargin) + SCREENH
        }
        
    }
    
    @objc private func btnClick(btn:YYEComposeButton) {
    
        UIView.animateWithDuration(1, animations: { () -> Void in
            for vale in self.buttons {
                
                if vale == btn {
                
                    btn.transform = CGAffineTransformMakeScale(2.0, 2.0)
                } else {
                
                    vale.transform = CGAffineTransformMakeScale(0.5, 0.5)
                }
                vale.alpha = 0.0
            }

            }) { (_) -> Void in
         
            // 动画完成,显示控件-------根据btn自己的信息进行弹出
               
              let classType = NSClassFromString(btn.menuInfo!.targetVC!)! as! UIViewController.Type
                
             // 注意 init没有智能提示
             let vc = classType.init()
                
                
                self.tagerVC?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                
               })
        }
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
    
         buttonsAnimation(true)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        buttonsAnimation(false)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * CGFloat(NSEC_PER_SEC))), dispatch_get_main_queue(), {
        
            self.removeFromSuperview()
        });

    }
    
    private func buttonsAnimation(isApper:Bool) {
    
    
        let  buttonsTmp = isApper ? buttons : buttons.reverse()
        
        for (i ,vale) in buttonsTmp
            .enumerate() {
                
                // 初始化动画
                
                let animation = POPSpringAnimation(propertyNamed:kPOPViewCenter)
                
                let valeInt = isApper ? -330:330
                
                animation.toValue = NSValue(CGPoint: CGPointMake(vale.center.x, vale.center.y + CGFloat(valeInt)))
                
                animation.springBounciness = 12
                
                animation.springSpeed = 7
                
                animation.beginTime = CACurrentMediaTime() + Double(i)*0.01
                
                vale.pop_addAnimation(animation, forKey: nil)
        }
    }


    // 截屏分数
    
    private func getUIScreen()->UIImage {
    
        let rect = UIScreen.mainScreen().bounds
        let window = UIApplication.sharedApplication().keyWindow!
        
        // 1. 开启图形的上下文
        // 参数1: 开启上下文大小,参数2是否透明,参数3如果是0就代表截取的是实际尺寸的大小,1的话是代码是点坐标大小
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        // 2. 将屏幕的内容画到上下文中
        window.drawViewHierarchyInRect(rect, afterScreenUpdates: false)
        // 3. 取到图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 4. 关闭上下文
        UIGraphicsEndImageContext()
        // 5. 返回图片
        return image
    }
    
    private lazy var adView:UIImageView = {
        let v = UIImageView(image: UIImage(named:"compose_slogan"))
        return v
    }()
    
    deinit {
        print("手动销毁 肯定释放 不惧强引用")
    }
}
